package com.newenergy.wisehome.ui.fragment;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.newenergy.wisehome.R;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.bean.FamilyUnique;
import com.newenergy.wisehome.data.ormlite.dao.FamilyDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyUniqueDao;

import butterknife.BindView;
import butterknife.OnClick;

/**
 *
 */
public class CreateFamilyFragment extends BaseFragment {


    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.tv_back)
    TextView mTvBack;
    @BindView(R.id.tv_page)
    TextView mTvPage;
    @BindView(R.id.btn_add)
    Button mBtnAdd;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.btn_confirm)
    Button mBtnConfirm;
    @BindView(R.id.btn_cancel)
    Button mBtnCancel;

    public CreateFamilyFragment() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_create_family;
    }

    @Override
    public void init(View rootView) {
        mTvPage.setText("新家创建");
    }


    @OnClick({R.id.btn_back, R.id.tv_back, R.id.btn_confirm, R.id
            .btn_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;
            case R.id.tv_back:
                doBack();
                break;
            case R.id.btn_confirm:
                createFamily();
                break;
            case R.id.btn_cancel:
                doBack();
                break;
        }
    }

    private void createFamily() {
        FamilyUniqueDao uniqueDao = new FamilyUniqueDao(getContext());
        FamilyDao familyDao = new FamilyDao(getContext());
        FamilyUnique familyUnique = uniqueDao.getByType(0);
        if (familyUnique == null) {
            myToast("创建家庭已经超出3个限制,不能再创建了。", true);
            return;
        }
        String name = mEtName.getText().toString().trim();
        if (checkFamilyName(name)) return;
        String fid = familyUnique.getFamilyId();
        familyDao.add(new Family(fid, name));
        familyUnique.setType(1);
        uniqueDao.update(familyUnique);

        myToast("创建家庭成功", false);
        doBack();

    }

}
